#!/usr/bin/env bash
# Summary: Show the current Go version
# Usage: goenv version-name
set -e
[ -n "$GOENV_DEBUG" ] && set -x

if [ -z "$GOENV_VERSION" ]; then
  GOENV_VERSION_FILE="$(goenv-version-file)"
  GOENV_VERSION="$(goenv-version-file-read "$GOENV_VERSION_FILE" || true)"
fi

OLDIFS="$IFS"
IFS=$'\n'
scripts=($(goenv-hooks version-name))
IFS="$OLDIFS"
for script in "${scripts[@]}"; do
  source "$script"
done

if [ -z "$GOENV_VERSION" ] || [ "$GOENV_VERSION" = "system" ]; then
  echo "system"
  exit
fi

version_exists() {
  local input_version="$1"
  local use_go_mod="$2"

  if [[ -n use_go_mod ]] && [[ -d ${GOENV_ROOT}/versions ]] && grep -q -E "^[0-9]+\.[0-9]+(\s*)$" <<<${input_version}; then
    OLDIFS="$IFS"
    IFS=$'\n'
    local version_regex=$(echo ${input_version} | sed s/\\./\\\\./)
    local versions=($(ls ${GOENV_ROOT}/versions | grep -E "^$version_regex(\\.[0-9]+)?$" | sort -V))
    IFS="$OLDIFS"
    if [[ ${#versions[@]} -eq 0 ]]; then
      return 1
    fi
    version=${versions[${#versions[@]} - 1]}
  fi

  [ -d "${GOENV_ROOT}/versions/${version}" ]
}

versions=()
OLDIFS="$IFS"
{
  IFS=:
  any_not_installed=0
  for version in ${GOENV_VERSION}; do
    if version_exists "$version" || [ "$version" = "system" ]; then
      versions=("${versions[@]}" "${version}")
    elif version_exists "${version#go-}"; then
      versions=("${versions[@]}" "${version#go-}")
    else
      if [[ -z $GOENV_GOMOD_VERSION_ENABLE ]] || ! version_exists "$version" "$GOENV_GOMOD_VERSION_ENABLE"; then
        echo "goenv: version '$version' is not installed (set by $(goenv-version-origin))" >&2
        any_not_installed=1
      fi
    fi
  done
}
IFS="$OLDIFS"

OLDIFS="$IFS"
{
  IFS=:
  echo "${versions[*]}"
}
IFS="$OLDIFS"

if [ "$any_not_installed" = 1 ]; then
  exit 1
fi
